<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Home\Controller;
use User\Api\UserApi;
vendor('phpqrcode.phpqrcode');

/**
 * 用户控制器
 * 包括用户中心，用户登录及注册
 */
class UserController extends HomeController {

	/* 用户中心首页 */
	public function index(){


//		print_r($_SESSION);
//		exit;
		if ( !is_login() ) {
			$this->error( '您还没有登陆',U('User/login') );
		}
		$title='账户中心';
			$uid=is_login();
		$user=M('Member')->where(array('uid'=>$uid))->find();
		$this->assign('user',$user);
		$this->assign('meta_title',$title);
//		echo   md5(sha1('123456') . 'YQ(d;62q,aiLr~uCRI`"/:g0$z[*S@8m|5U4]vps');
		$this->display();
	}

	/* 注册页面 */
	public function register($username = '', $password = '', $repassword = '', $email = '', $verify = ''){
        if(!C('USER_ALLOW_REGISTER')){
            $this->error('注册已关闭');
        }
		if(IS_POST){ //注册用户
			/* 检测验证码 */
			if(!check_verify($verify)){
				$this->error('验证码输入错误！');
			}
			/* 检测密码 */
			if($password != $repassword){
				$this->error('密码和重复密码不一致！');
			}			

			/* 调用注册接口注册用户 */
            $User = new UserApi;
			$uid = $User->register($username, $password, $email);
			if(0 < $uid){ //注册成功
				//TODO: 发送验证邮件
				$this->success('注册成功！',U('login'));
			} else { //注册失败，显示错误信息
				$this->error($this->showRegError($uid));
			}

		} else { //显示注册表单
			$this->display();
		}
	}

	/* 登录页面 */
	public function login($username = '', $password = '', $verify = ''){
		if(IS_POST){ //登录验证
			/* 调用UC登录接口登录 */
			$user = new UserApi;
			$uid = $user->login($username, $password);
			if(0 < $uid){ //UC登录成功
				/* 登录用户 */
				$Member = D('Member');
				if($Member->login($uid)){ //登录用户
					//TODO:跳转到登录前页面
					$this->success('登录成功！',U('Home/User/index'));
				} else {
					$this->error($Member->getError());
				}

			} else { //登录失败
				switch($uid) {
					case -1: $error = '用户不存在或被禁用！'; break; //系统级别禁用
					case -2: $error = '密码错误！'; break;
					default: $error = '未知错误！'; break; // 0-接口参数错误（调试阶段使用）
				}
				$this->error($error);
			}
		} else { //显示登录表单
//					echo   md5(sha1('123456') . 'YQ(d;62q,aiLr~uCRI`"/:g0$z[*S@8m|5U4]vps');
			$this->display();
		}
	}



	/* 退出登录 */
	public function logout(){
		if(is_login()){
			D('Member')->logout();
			$this->success('退出成功！', U('User/login'));
		} else {
			$this->redirect('User/login');
		}
	}

	/* 验证码，用于登录和注册 */
	public function verify(){
		$config =    array(
				'length'      =>    4,     // 验证码位数
		);
		$verify = new \Think\Verify($config);
		$verify->codeSet = '0123456789';
		$verify->entry(1);
	}

	/**
	 * 获取用户注册错误信息
	 * @param  integer $code 错误编码
	 * @return string        错误信息
	 */
	private function showRegError($code = 0){
		switch ($code) {
			case -1:  $error = '用户名长度必须在16个字符以内！'; break;
			case -2:  $error = '用户名被禁止注册！'; break;
			case -3:  $error = '用户名被占用！'; break;
			case -4:  $error = '密码长度必须在6-30个字符之间！'; break;
			case -5:  $error = '邮箱格式不正确！'; break;
			case -6:  $error = '邮箱长度必须在1-32个字符之间！'; break;
			case -7:  $error = '邮箱被禁止注册！'; break;
			case -8:  $error = '邮箱被占用！'; break;
			case -9:  $error = '手机格式不正确！'; break;
			case -10: $error = '手机被禁止注册！'; break;
			case -11: $error = '手机号被占用！'; break;
			default:  $error = '未知错误';
		}
		return $error;
	}


    /**
     * 修改密码提交
     * @author huajie <banhuajie@163.com>
     */
    public function profile(){
		if ( !is_login() ) {
			$this->error( '您还没有登陆',U('User/login') );
		}
        if ( IS_POST ) {
            //获取参数
            $uid        =   is_login();
            $password   =   I('post.old');
            $repassword = I('post.repassword');
            $data['password'] = I('post.password');
            empty($password) && $this->error('请输入原密码');
            empty($data['password']) && $this->error('请输入新密码');
            empty($repassword) && $this->error('请输入确认密码');
            if($data['password'] !== $repassword){
                $this->error('您输入的新密码与确认密码不一致');
            }
            $Api = new UserApi();
            $res = $Api->updateInfo($uid, $password, $data);
            if($res['status']){
                $this->success('修改密码成功！');
            }else{
                $this->error($res['info']);
            }
        }else{
            $this->display();
        }
    }
	/**账户资料
	 **/
	public function  material(){
		if ( !is_login() ) {
			$this->error( '您还没有登陆',U('User/login') );
		}
		$title='我的资料';
		$uid     =   is_login();
		$user=M('Member')->where(array('uid'=>$uid))->find();
		$user['username']=get_username($uid);
		$this->assign('data',$user);
		$this->assign('meta_title',$title);
		$this->display();
	}

	/**
	 * 编辑资料
	 */
	public function editorial(){
		if ( !is_login() ) {
			$this->error( '您还没有登陆',U('User/login') );
		}
		$title='编辑资料';
		$uid     =   is_login();
		$user=M('Member')->where(array('uid'=>$uid))->find();
		$this->assign('data',$user);
		$this->assign('meta_title',$title);
		$this->display();
	}
	/***
	 * 保存资料
	 */
	public function saverial(){
		if(IS_AJAX){
			//手机号码 JC_TEL
			$uid     =   is_login();
			if(!$this->JC_TEL($_POST['Tel'])){
				echo 2;
				exit;
			}
			// 银行卡账号错误BankNum
			if(!$this->JC_BK($_POST['BankNum'])){
				echo 2;
				exit;
			}
			//   身份证号码错误
			if(!$this->JC_CD($_POST['IdCard'])){
				echo 3;
				exit;
			}
			$data['phone']=$_POST['Tel'];  //手机
			$data['bank']=$_POST['BankName']; //开户银行
			$data['bank_no']=$_POST['BankNum'];  //银行账号
			$data['realname']=$_POST['UserName']; //真实姓名
			$data['nickname']=$_POST['UserRealName']; //昵称
			$data['sex']=$_POST['Sex'];   //性别
			$data['card']=$_POST['IdCard'];  //身份证
			$data['province']=$_POST['Province'];  //s省份
			$data['city']=$_POST['City'];   //地区
			$data['detailed']=$_POST['Town'];
			$info=M('Member')->where(array('uid'=>$uid))->save($data);
			$msg['password']=md5(sha1($_POST['UserPass']) . 'YQ(d;62q,aiLr~uCRI`"/:g0$z[*S@8m|5U4]vps');
			$infos=M('UcenterMember')->where(array('id'=>$uid))->save($msg);
				if($info && $infos){
						$arr=array(
							'state'=>1,
							'info'=>'保存成功',
							'url'=>'User/material'
						);
					$this->ajaxReturn($arr);
				}else{
					$arr=array(
							'state'=>0,
							'info'=>'保存失败'
					);
					$this->ajaxReturn($arr);
				}
		}
	}

	/**
	 * 我的农场
	 */
	public function farm(){
		if ( !is_login() ) {
			$this->error( '您还没有登陆',U('User/login') );
		}
		$title='我的农场';
		$uid=is_login();
		$user=M('Member')->where(array('uid'=>$uid))->find();
		$this->assign('user',$user);
		$this->assign('meta_title',$title);
		$this->display();
	}
	/**
	 * 资金流水
	 */
	public function capital(){
		if ( !is_login() ) {
			$this->error( '您还没有登陆',U('User/login') );
		}
		$title='我的收支';
		$this->assign('meta_title',$title);
		$this->display();
	}


	/**
	 * 充值
	 */
	public function recharge(){
		if ( !is_login() ) {
			$this->error( '您还没有登陆',U('User/login') );
		}
		$title='积分充值';
		$this->assign('meta_title',$title);
		$this->display();
	}
	/**
	 *   商城收益
	 */
	public function mall(){
		if ( !is_login() ) {
			$this->error( '您还没有登陆',U('User/login') );
		}
		$title='商超收益';
		$this->assign('meta_title',$title);
		$this->display();
	}
	/**
	 *  推广二维码
	 */
	public function extend(){
		if ( !is_login() ) {
			$this->error( '您还没有登陆',U('User/login') );
		}
		$member = 1;
		$QRcode = new \Think\Qrcode;
		$path = '/dndj/ewm';
		$userpath = $path .'/'. $member; //用户二微码目录
		$value = U('User/register',array('ac'=>$member));
		if(!is_dir($userpath)) {
			mkdir($userpath, 0777, true);
		}
		$errorCorrectionLevel = 'L';//纠错级别：L、M、Q、H
		$matrixPointSize = 10;//二维码点的大小：1到10
		$QRcode::png ( $value, $userpath . '/ewm.png', $errorCorrectionLevel, $matrixPointSize, 2 );//不带Logo二维码的文件名
		$logo = dirname(__APP__). '/dndj/dndj.jpg';//需要显示在二维码中的Logo图像
		$QR = $userpath . '/ewm.png';
		if ($logo !== FALSE) {
			$QR = imagecreatefromstring ( file_get_contents ( $QR ) );
			$logo = imagecreatefromstring ( file_get_contents ( $logo ) );
			$QR_width = imagesx ( $QR );
			$QR_height = imagesy ( $QR );
			$logo_width = imagesx ( $logo );
			$logo_height = imagesy ( $logo );
			$logo_qr_width = $QR_width / 5;
			$scale = $logo_width / $logo_qr_width;
			$logo_qr_height = $logo_height / $scale;
			$from_width = ($QR_width - $logo_qr_width) / 2;
			imagecopyresampled ( $QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height );
		}
		imagepng ( $QR, 'ewmlogo.png' );//带Logo二维码的文件名
		$title='推广二维码';
		$this->assign('meta_title',$title);
		$this->display();
	}
}

